%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%openDACS projects%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Main optimization routine written for A-IGZO TETs
%%% Print parameters or self-generate Verilog-A
%%% About a-IGZO devices and models,pls refer 10.1063/1.4922181,10.1109/TED.2021.3054359
%%% developed by Jingrui Guo,Lingfei Wang, and Ling Li from IME-CAS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
close all
clear
clc
%%%%%%%%%%%%%%if Print%%%%%%%%
ifprint=str2num(input('0:Just plot|1:Print parms and figures|2:Print VA code\n:', 's'));
%%%%% get structure imformation %%%%%%%%%
get_value= input('Enter the list of fixed [Tem,L,w,Ci,Fs,lleak],e.g,[300,6.0e-6,4.0e-6,1.24e-8,8,0.5e-12]\n:', 's');
fix_value=str2num(get_value);
%%%%% Temperature %%%%%%%%%
Tem=fix_value(1);
%%%%% Fixed Coeff_structure %%%%%%%%%
l =fix_value(2); %length value fixed  10.0e-6
w =fix_value(3); % width  value fixed 90.0e-6
Ci=fix_value(4);%unit-area capacitance	F/cm2		value fixed 
Fs=fix_value(5); %relative permittivity constant for channel material value fixed 
lleak=fix_value(6);%leakage current 
%%%% Optimized Coeff_fit parameters
TA = 450;%characteristic temperature	[200,1000]
Nt = 1.5e15;%carrier density 	value fixed
n = 5;%formula fitting parameter1	[0.1,10]
m = 1 ;%formula fitting parameter2	[0.1,10]
ss =2.75;%formula fitting parameter3	[0.1,10] tune the subslope
Vfb = 0.5;%flat-band voltage	[-1,2]
Ue = 15;%mobility [10,50] 
y = 0.1;%channel length modulation parameter [0,1]
ScaleVd=0.1;%channel leakage [0,10000]
ScaleVg=1.1;%channel leakage [0,10000]
FVd=0.1;%current correction [0,1]
%%% define global inputs
global input_parms TolFun
input_parms =[Tem;l;w;Ci;Fs;lleak;TA;Nt;n;m;ss;Vfb;Ue;y;ScaleVd;ScaleVg;FVd];
coeff_structure=input_parms(1:6);
coeff_fit=input_parms(7:end);

global IdVg bias_data Id_data
% User input for the experimental data with the correct path
path_data=input('Input path (optional) or just push ENTER to skip,e.g,D:\\OD_TFT_v_1_0_5\\Optimal Parameter Module\\\n:', 's');
expt_data = [path_data,'data\',input('Enter the name of experimental data file,e.g.,Sample_3_Total_W4_L6\n:', 's'),'.txt'];
IdVg = (dlmread(expt_data));
Vg_data=IdVg(1:end,1);
Vd_data=IdVg(1:end,2);
clear bias_data*
bias_data(:,1)=Vg_data;
bias_data(:,2)=Vd_data;
%%% define a matrix of intial coefficients 
coeff_init = coeff_fit;
[coeff_op] = real(optimize_data(coeff_init)); % 1st iteration
% Number of iterations
iter=5;
%%%%%% Tolerence control
TolFun=1e-15;
for len_iter=2:iter
[coeff_op(:,len_iter)] = real(optimize_data(coeff_op(:,len_iter-1)));
end
coeff_op_final=real(coeff_op(:,end));
Id=OD_TFT_v_1_0_3(coeff_op_final,bias_data);

%plot experimental data and cooresponding simualations
plot_curves(bias_data,Id,Id_data)
%Writing optimized coefficients in /self-coded/parms.txt.
if ifprint==1 
parms_print(coeff_op_final)
print_curves();
end

%Writing VA in /self-coded
if ifprint==2 
self_coded(coeff_op_final)
end


